const sql = require('./sql');
const iconv = require('iconv-lite');
const request = require('request-promise');

async function getUserId(html) {
  //从页面 html 中 查找
  let match;
  if (!html) html = await this.fetchGBKPage(url);
  match = html.match(/"userId":[0-9]+/);
  if (match) return match[0].slice(9);
  match = html.match(/userId=[0-9]+/);
  if (match) return match[0].slice(7);
  return null;
}

async function getUserIdAndSkuIds(goodPage) {
  var bufs = await request.get(goodPage, { encoding: null });
  bufs = iconv.decode(bufs, 'gb2312');
  //转为utf8
  const html = bufs.toString('utf8');

  const skuIds = [];
  const match = html.match(/"skuId":"[0-9]+"/g);
  if (match && match.length > 0) {
    match.forEach(i => skuIds.push(i.slice(9, -1)));
  }
  const arr = Array.from(new Set(skuIds));
  const skuids = arr.length <= 0 ? null : arr.join();
  const userId = await getUserId(html)
  return {
    userId, skuids
  }
}

exports.test = async function (req, res) {
  res.writeHead(200, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify({ error: 0, str: 'str' }));
};

function typeEx(tmp) {
  if (tmp.isWang === 1) {
    tmp.type = '旺旺';
  }
  if (tmp.isCoupon === 1) {
    tmp.type = tmp.type + '+' +
      '优惠券';
  }
  if (tmp.isCart === 1) {
    tmp.type = tmp.type + '+' +
      '加购';
  }
  if (tmp.isFollow === 1) {
    tmp.type = tmp.type + '+' +
      '关注';
  }
  return tmp;
}
// 登陆验证
exports.login = function (req, res) {
  let vm = {};
  let sqlite = 'SELECT * FROM account Where username=' +
    '"' + req.body.account + '"' +
    ' and password=' +
    '"' + req.body.password + '"';
  sql.query(sqlite).then(data => {
    if (data.length) {
      let sqlite2 = 'SELECT id FROM account Where top_id=' +
        '"' + data[0].id + '"';
      sql.query(sqlite2).then(tmp => {
        let array_id = [];
        vm.isok = true;
        vm.msg = '查找到数据';
        vm.id = data[0].id;
        vm.account = data[0].username;
        vm.accountType = data[0].type;
        vm.open = {
          openWang: data[0].openWang,
          openCart: data[0].openCart,
          openFollow: data[0].openFollow,
          openCoupon: data[0].openCoupon,
        }
        let d = new Date(data[0].exp);
        vm.date = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate();
        array_id.push(data[0].id);
        for (let i = 0, len = tmp.length; i < len; i++) {
          array_id.push(tmp[i].id);
        }
        vm.ids = array_id;
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify(vm));
      });
    } else {
      vm.isok = false;
      vm.msg = '您输入的帐号或者密码不正确，请重新输入。';
      res.writeHead(200, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify(vm));
    }
  });
};
//检测账号名
exports.loginCheck = function (req, res) {
  let vm = {};
  let sqlite = 'SELECT * FROM account Where username=' +
    '"' + req.body.account + '"';
  sql.query(sqlite).then(data => {
    if (data.length) {
      vm.isok = true;
      vm.msg = '已有账号请重新输入';
    } else {
      vm.isok = false;
      vm.msg = '账号可注册';
    }
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify(vm));
  });
};

//生成
exports.build = async function (req, res) {
  let reb = req.body;
  let vm = {};
  let addSql =
    'INSERT INTO urls(isWang,isCoupon,isCart,isFollow,goodPage,couponPage,landingPage,mark,owner,ownername,skuids) VALUES(?,?,?,?,?,?,?,?,?,?,?)';

  let skuids;
  if (reb.isCart && reb.goodPage) {
    temp = await getUserIdAndSkuIds(reb.goodPage);
    skuids = temp.skuids;
    const userId = temp.userId;
    const account =
      await sql.query('SELECT * FROM account WHERE id = ' + reb.owner)
    const tbUserId = account[0]['tbUserId'];
    if (userId != tbUserId) {
      vm.isok = false
      vm.msg = '加购宝贝不属于您店铺'
      res.writeHead(200, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify(vm));
      return;
    }
  }



  let addSqlParams = [
    reb.isWang, reb.isCoupon, reb.isCart, reb.isFollow, reb.goodPage,
    reb.couponPage, reb.landingPage, reb.mark, reb.owner, reb.ownername, skuids
  ];

  sql.insert(addSql, addSqlParams).then(data => {
    if (data) {
      vm.isok = true;
      vm.msg = '添加成功';
    } else {
      vm.isok = false;
      vm.msg = '添加失败';
    }
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify(vm));
  });
};

//生成
exports.addWang = async function (req, res) {
  let reb = req.body;
  let vm = {};
  let addSql = 'INSERT INTO wang(ip,updateAt,urlId,username) VALUES(?,?,?,?)';


  let addSqlParams = [req.query.ip, new Date(), req.query.urlId, req.query.username];

  sql.insert(addSql, addSqlParams).then(data => {
    if (data) {
      vm.isok = true;
      vm.msg = '添加成功';
    } else {
      vm.isok = false;
      vm.msg = '添加失败';
    }
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify(vm));
  });
};


// 生成记录列表
exports.buildRecord = function (req, res) {
  let reb = req.body;
  let sqlite = 'SELECT * FROM urls Where owner in' +
    '(' + reb.id + ')' +
    ' ORDER BY updateAt DESC' +
    ' Limit ' + (reb.pageindex - 1) * reb.pagesize + ',' + reb.pagesize;
  let sqlength = 'SELECT COUNT(*) From urls where owner in' + '(' + reb.id + ')';
  if (reb.type === 'admin') {
    sqlite = 'SELECT * FROM urls' +
      ' ORDER BY updateAt DESC' +
      ' Limit ' + (reb.pageindex - 1) * reb.pagesize + ',' + reb.pagesize;
    sqlength = 'SELECT COUNT(*) From urls';
  }
  sql.queryLst(sqlite, sqlength).then(data => {
    for (let i = 0, len = data.lst.length; i < len; i++) {
      data.lst[i].type = '';
      data.lst[i] = typeEx(data.lst[i]);
    }
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify(data));
  });
};
//删除记录
exports.buildDel = function (req, res) {
  let vm = {};
  let delSql = 'DELETE FROM wangwang where urlsId=' + req.body.id;
  let delSql2 = 'DELETE FROM urls where id=' + req.body.id;

  sql.query(delSql).then(data => {
    sql.query(delSql2).then(tm => {
      if (tm) {
        vm.isok = true;
        vm.msg = '删除成功';
      } else {
        vm.isok = false;
        vm.msg = '删除失败';
      }
      res.writeHead(200, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify(vm));
    });
  });
};
//修改记录
exports.buildUpdate = function (req, res) {
  let vm = {};
  let reb = req.body;
  let updateSql =
    'UPDATE urls SET isWang=?,isCoupon=?,isCart=?,isFollow=?,goodPage=?,couponPage=?,landingPage=?,mark=?WHERE Id=?';
  let updateSqlParams = [
    reb.isWang, reb.isCoupon, reb.isCart, reb.isFollow, reb.goodPage,
    reb.couponPage, reb.landingPage, reb.mark, reb.id
  ];
  sql.insert(updateSql, updateSqlParams).then(data => {
    if (data) {
      vm.isok = true;
      vm.msg = '更新成功';
    } else {
      vm.isok = false;
      vm.msg = '更新失败';
    }
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify(vm));
  });
};
//注册
exports.register = function (req, res) {
  let vm = {};
  let reb = req.body;
  let addSql =
    'INSERT INTO account(username,password,exp,type,cash,top_id,tbUserId,openWang,openCart,openFollow,openCoupon,mark) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)';
  let addSqlParams = [
    reb.account, reb.password, reb.date, reb.accountType, reb.money, reb.by_id,
    reb.tbUserId, reb.openWang, reb.openCart, reb.openFollow, reb.openCoupon, reb.mark
  ];
  sql.insert(addSql, addSqlParams).then(data => {
    if (data) {
      vm.isok = true;
      vm.msg = '开通成功';
    } else {
      vm.isok = false;
      vm.msg = '开通失败';
    }
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify(vm));
  });
};
//账号列表信息
exports.loginLst = function (req, res) {
  let reb = req.body;
  let sqlite = 'SELECT * FROM account Where top_id=' + '"' + reb.id + '"' + ' ORDER BY exp ' + reb.sort + ' Limit ' + (reb.pageindex - 1) * reb.pagesize + ',' + reb.pagesize;
  let sqlength = 'SELECT COUNT(*) From account where top_id=' + reb.id;
  if (reb.type === 'admin') {
    sqlite = 'SELECT * FROM account' + ' ORDER BY exp ' + reb.sort + ' Limit ' + (reb.pageindex - 1) * reb.pagesize + ',' + reb.pagesize;
    sqlength = 'SELECT COUNT(*) From account';
  }
  sql.queryLst(sqlite, sqlength).then(data => {
    for (let i = 0, len = data.lst.length; i < len; i++) {
      let d = new Date(data.lst[i].exp);
      data.lst[i].date =
        d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate();
    }
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify(data));
  });
};

//充值
exports.updateMoney = function (req, res) {
  let vm = {};
  let reb = req.body;
  let updateSql = 'UPDATE account SET cash=? WHERE Id=?';
  let updateSqlParams = [];
  let sqlite = 'SELECT * FROM account Where Id=' +
    '"' + reb.id + '"';
  sql.query(sqlite).then(data => {
    if (data) {
      let money = Number(data[0].cash) + Number(reb.money);
      updateSqlParams = [money, reb.id];
      sql.insert(updateSql, updateSqlParams).then(tmp => {
        if (tmp) {
          vm.isok = true;
          vm.msg = '充值成功';
        } else {
          vm.isok = false;
          vm.msg = '充值失败';
        }
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify(vm));
      });
    }
  });
};
//查看旺旺列表
exports.wangwangLst = function (req, res) {
  let reb = req.body;
  let sqlite = 'SELECT * FROM wang Where urlId=' +
    '"' + reb.urlsId + '"' +
    ' ORDER BY updateAt DESC' +
    ' Limit ' + (reb.pageindex - 1) * reb.pagesize + ',' + reb.pagesize;
  let sqlength = 'SELECT COUNT(*) From wang where urlId=' + reb.urlsId;

  sql.queryLst(sqlite, sqlength).then(data => {
    for (let i = 0, len = data.lst.length; i < len; i++) {
      let d = new Date(data.lst[i].updateAt);
      data.lst[i].updateAt = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' +
        d.getDate() + '  ' + d.getHours() + ':' + d.getMinutes() + ':' +
        d.getSeconds();
    }
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify(data));
  });
};

//搜索生成记录
exports.searchRecord = function (req, res) {
  let vm = {};
  let reb = req.body;
  let sqlite = 'SELECT * FROM urls Where owner in' +
    '(' + reb.ids + ')' +
    ' and' +
    ' (goodPage=' +
    '"' + reb.searchLink + '"' +
    ' or couponPage=' +
    '"' + reb.searchLink + '"' +
    ' or landingPage=' +
    '"' + reb.searchLink + '"' + ' or Id=' +
    '"' + reb.searchLink + '"' + ' or mark=' +
    '"' + reb.searchLink + '"' + ' or ownername=' +
    '"' + reb.searchLink + '"' +
    ')';
  if (reb.type === 'admin') {
    sqlite = 'SELECT * FROM urls Where  goodPage=' +
      '"' + reb.searchLink + '"' +
      ' or couponPage=' +
      '"' + reb.searchLink + '"' +
      ' or landingPage=' +
      '"' + reb.searchLink + '"' + ' or Id=' +
      '"' + reb.searchLink + '"' + ' or mark=' +
      '"' + reb.searchLink + '"' + ' or ownername=' +
      '"' + reb.searchLink + '"';
  }

  sql.query(sqlite).then(data => {
    if (data.length) {
      vm.isok = true;
      vm.msg = '查询成功';
      for (let i = 0, len = data.length; i < len; i++) {
        data[i].type = '';
        data[i] = typeEx(data[i]);
      }
      vm.lst = data;
    } else {
      vm.isok = false;
      vm.msg = '查询失败';
      vm.lst = [];
    }
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify(vm));
  });
};
//筛选类型
exports.fifterRecord = function (req, res) {
  let vm = {};
  let reb = req.body;
  let sqlite = 'SELECT * FROM urls Where owner in ' + '(' + reb.ids + ')' + ' and ';
  if (reb.type === 'admin') {
    sqlite = 'SELECT * FROM urls Where';
  }
  if (reb.isWang === '1') {
    sqlite = sqlite + ' isWang=' + '"' + reb.isWang + '"';
  }
  if (reb.isCart === '1') {
    sqlite = sqlite + ' isCart=' + '"' + reb.isCart + '"';
  }
  if (reb.isCoupon === '1') {
    sqlite = sqlite + ' isCoupon=' + '"' + reb.isCoupon + '"';
  }
  if (reb.isFollow === '1') {
    sqlite = sqlite + ' isFollow=' + '"' + reb.isFollow + '"';
  }

  sql.query(sqlite).then(data => {
    if (data.length) {
      vm.isok = true;
      vm.msg = '查询成功';
      for (let i = 0, len = data.length; i < len; i++) {
        data[i].type = '';
        data[i] = typeEx(data[i]);
      }
      vm.lst = data;
    } else {
      vm.isok = false;
      vm.msg = '查询失败';
      vm.lst = [];
    }
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify(vm));
  });
};

//搜索店铺
exports.searchOwn = function (req, res) {
  let vm = {};
  let reb = req.body;
  let sqlite = 'SELECT * FROM urls Where ownername=' +
    '"' + reb.ownername + '"';
  sql.query(sqlite).then(data => {
    if (data.length) {
      vm.isok = true;
      vm.msg = '查询成功';
      for (let i = 0, len = data.length; i < len; i++) {
        data[i].type = '';
        data[i] = typeEx(data[i]);
      }
      vm.lst = data;
    } else {
      vm.isok = false;
      vm.msg = '查询失败';
      vm.lst = [];
    }
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify(vm));
  });
};

//更新到期日期
exports.updateTime = function (req, res) {
  let vm = {};
  let reb = req.body;
  let updateSql = 'UPDATE account SET exp=? WHERE Id=?';
  let updateSqlParams = [reb.exp, reb.id];
  sql.insert(updateSql, updateSqlParams).then(tmp => {
    if (tmp) {
      vm.isok = true;
      vm.msg = '更新成功';
    } else {
      vm.isok = false;
      vm.msg = '更新失败';
    }
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify(vm));
  });
};
//筛选账号类型
exports.searchAccount = function (req, res) {
  let vm = {};
  let reb = req.body;
  let sqlite = 'SELECT * FROM account Where top_id in' +
    '(' + reb.ids + ')' +
    ' and username like' +
    '"%' + reb.username + '%"';
  if (reb.type === 'admin') {
    sqlite = 'SELECT * FROM account Where  username like' +
      '"%' + reb.username + '%"';
  }
  sql.query(sqlite).then(data => {
    if (data.length) {
      vm.isok = true;
      vm.msg = '查询成功';
      vm.lst = data;
    } else {
      vm.isok = false;
      vm.msg = '查询失败';
      vm.lst = [];
    }
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify(vm));
  });
};

//更新到期日期
exports.updateFunc = function (req, res) {
  let vm = {};
  let reb = req.body;
  let updateSql = 'UPDATE account SET openCart=?,openCoupon=?,openFollow=?,openWang=? WHERE Id=?';
  let updateSqlParams = [reb.openCart, reb.openCoupon, reb.openFollow, reb.openWang, reb.id];
  sql.insert(updateSql, updateSqlParams).then(tmp => {
    if (tmp) {
      vm.isok = true;
      vm.msg = '更新成功';
    } else {
      vm.isok = false;
      vm.msg = '更新失败';
    }
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify(vm));
  });
};

//修改密码
exports.updatePassword = function (req, res) {
  let vm = {};
  let reb = req.body;
  let updateSql = 'UPDATE account SET password=? WHERE Id=?';
  let updateSqlParams = [reb.password, reb.id];
  sql.insert(updateSql, updateSqlParams).then(tmp => {
    if (tmp) {
      vm.isok = true;
      vm.msg = '修改成功';
    } else {
      vm.isok = false;
      vm.msg = '修改失败';
    }
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify(vm));
  });
};


//删除账号
exports.accountDel = async function (req, res) {
  let vm = {};
  let sqlite = 'SELECT * FROM urls Where owner=' + '"' + req.body.id + '"';
  let delSql = 'DELETE FROM account where Id=' + req.body.id;
  let delSql2 = 'DELETE FROM urls where owner=' + req.body.id;
  let urlsData = await sql.query(sqlite)
  let delSql3 = 'DELETE FROM wang where urlId=' + urlsData.id;
  sql.query(delSql3).then(dl3 => {
    if (dl3) {
      sql.query(delSql2).then(async dl2 => {
        if (dl2) {
          let delaccount = await sql.query(delSql)
          if (delaccount) {
            vm.isok = true;
            vm.msg = '删除成功';
          } else {
            vm.isok = false;
            vm.msg = '删除失败';
          }
          res.writeHead(200, { 'Content-Type': 'application/json' });
          res.end(JSON.stringify(vm));
        }
      })
    }
  })

};